package org.example.lanchain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.lanchain.bean.ApiKey;
import org.example.lanchain.mapper.ApiKeyMapper;
import org.example.lanchain.service.ApiKeyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.List;

/**
 * API Key服务实现类
 */
@Service
public class ApiKeyServiceImpl extends ServiceImpl<ApiKeyMapper, ApiKey> implements ApiKeyService {

    private static final Logger logger = LoggerFactory.getLogger(ApiKeyServiceImpl.class);
    
    private static final String API_KEY_PREFIX = "xz-";
    private static final int API_KEY_LENGTH = 48;
    private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
    private final SecureRandom random = new SecureRandom();

    @Override
    public ApiKey createApiKey(Long userId, String name) {
        try {
            // 生成唯一的API Key
            String apiKey = generateUniqueApiKey();
            
            // 创建API Key对象
            ApiKey newApiKey = new ApiKey(userId, name, apiKey);
            
            // 保存到数据库
            boolean saved = save(newApiKey);
            if (!saved) {
                throw new RuntimeException("API Key保存失败");
            }
            
            logger.info("用户 {} 创建了新的API Key: {}", userId, name);
            return newApiKey;
        } catch (Exception e) {
            logger.error("创建API Key失败", e);
            throw new RuntimeException("API Key创建失败: " + e.getMessage());
        }
    }

    @Override
    public List<ApiKey> getUserApiKeys(Long userId) {
        QueryWrapper<ApiKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("create_time");
        return list(queryWrapper);
    }

    @Override
    public boolean deleteApiKey(Long id, Long userId) {
        try {
            // 验证权限
            ApiKey apiKey = getById(id);
            if (apiKey == null || !apiKey.getUserId().equals(userId)) {
                logger.warn("用户 {} 尝试删除不属于自己的API Key: {}", userId, id);
                return false;
            }
            
            boolean deleted = removeById(id);
            if (deleted) {
                logger.info("用户 {} 删除了API Key: {}", userId, apiKey.getName());
            }
            return deleted;
        } catch (Exception e) {
            logger.error("删除API Key失败", e);
            return false;
        }
    }

    @Override
    public boolean updateApiKeyName(Long id, Long userId, String name) {
        try {
            // 验证权限
            ApiKey apiKey = getById(id);
            if (apiKey == null || !apiKey.getUserId().equals(userId)) {
                logger.warn("用户 {} 尝试修改不属于自己的API Key: {}", userId, id);
                return false;
            }
            
            apiKey.setName(name);
            apiKey.setUpdateTime(LocalDateTime.now());
            boolean updated = updateById(apiKey);
            
            if (updated) {
                logger.info("用户 {} 更新了API Key名称: {} -> {}", userId, apiKey.getName(), name);
            }
            return updated;
        } catch (Exception e) {
            logger.error("更新API Key名称失败", e);
            return false;
        }
    }

    @Override
    public ApiKey regenerateApiKey(Long id, Long userId) {
        try {
            // 验证权限
            ApiKey apiKey = getById(id);
            if (apiKey == null || !apiKey.getUserId().equals(userId)) {
                logger.warn("用户 {} 尝试重新生成不属于自己的API Key: {}", userId, id);
                return null;
            }
            
            // 生成新的API Key值
            String newApiKeyValue = generateUniqueApiKey();
            apiKey.setApiKey(newApiKeyValue);
            apiKey.setUsageCount(0L);
            apiKey.setLastUsedAt(null);
            apiKey.setUpdateTime(LocalDateTime.now());
            
            boolean updated = updateById(apiKey);
            if (updated) {
                logger.info("用户 {} 重新生成了API Key: {}", userId, apiKey.getName());
                return apiKey;
            }
            return null;
        } catch (Exception e) {
            logger.error("重新生成API Key失败", e);
            return null;
        }
    }

    @Override
    public boolean validateApiKey(String apiKey) {
        if (apiKey == null || apiKey.trim().isEmpty()) {
            return false;
        }
        
        QueryWrapper<ApiKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("api_key", apiKey)
                   .eq("status", "active");
        
        ApiKey key = getOne(queryWrapper);
        
        // 检查是否过期
        if (key != null && key.getExpiresAt() != null) {
            return key.getExpiresAt().isAfter(LocalDateTime.now());
        }
        
        return key != null;
    }

    @Override
    public ApiKey getByApiKey(String apiKey) {
        QueryWrapper<ApiKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("api_key", apiKey);
        return getOne(queryWrapper);
    }

    @Override
    public void updateUsageStats(String apiKey) {
        try {
            baseMapper.updateUsageStats(apiKey, LocalDateTime.now());
        } catch (Exception e) {
            logger.error("更新API Key使用统计失败", e);
        }
    }

    /**
     * 生成唯一的API Key
     */
    private String generateUniqueApiKey() {
        String apiKey;
        int attempts = 0;
        do {
            apiKey = generateApiKey();
            attempts++;
            if (attempts > 10) {
                throw new RuntimeException("生成唯一API Key失败，请重试");
            }
        } while (isApiKeyExists(apiKey));
        
        return apiKey;
    }

    /**
     * 生成随机API Key
     */
    private String generateApiKey() {
        StringBuilder sb = new StringBuilder(API_KEY_PREFIX);
        for (int i = 0; i < API_KEY_LENGTH - API_KEY_PREFIX.length(); i++) {
            sb.append(CHARS.charAt(random.nextInt(CHARS.length())));
        }
        return sb.toString();
    }

    /**
     * 检查API Key是否已存在
     */
    private boolean isApiKeyExists(String apiKey) {
        QueryWrapper<ApiKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("api_key", apiKey);
        return count(queryWrapper) > 0;
    }
}